package com.zxl.yjb.activity.home.order;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptor;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MarkerOptions;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.zxl.yjb.GlideApp;
import com.zxl.yjb.R;
import com.zxl.yjb.adapter.ImageAdapter;
import com.zxl.yjb.base.BaseActivity;
import com.zxl.yjb.bean.LoginSucessBean;
import com.zxl.yjb.bean.ReasonBean;
import com.zxl.yjb.bean.SosDetailBean;
import com.zxl.yjb.http.HostUrl;
import com.zxl.yjb.http.manager.DataManager;
import com.zxl.yjb.http.observer.ObserverOnNextListener;
import com.zxl.yjb.http.observer.ProgressObserver;
import com.zxl.yjb.im.utils.RongChatUtils;
import com.zxl.yjb.utils.CheckApplacationUtil;
import com.zxl.yjb.utils.DisplayUtil;
import com.zxl.yjb.utils.GPSUtil;
import com.zxl.yjb.utils.PickerViewUtils;
import com.zxl.yjb.utils.SaveBeanUtil;
import com.zxl.yjb.utils.ToastUtils;
import com.zxl.yjb.voiceplayer.EaseChatRowVoicePlayer;
import com.zxl.yjb.voiceplayer.IMAudioManager;
import com.zxl.yjb.widget.CircleImageView;
import com.zxl.yjb.widget.MapContainer;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SosDetailActivity extends BaseActivity {
    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.iv_confirm2)
    ImageView iv_confirm2;
    @BindView(R.id.tv_confirm)
    TextView tv_confirm;
    @BindView(R.id.tv_user_name)
    TextView tv_user_name;
    @BindView(R.id.tv_orderdetail_id)
    TextView tv_orderdetail_id;
    @BindView(R.id.tv_order_type)
    TextView tv_order_type;
    @BindView(R.id.tv_order_endtime)
    TextView tv_order_endtime;
    @BindView(R.id.tv_content)
    TextView tv_content;
    @BindView(R.id.rv_pic)
    RecyclerView rv_pic;
    @BindView(R.id.tv_reedit)
    TextView tv_reedit;
    @BindView(R.id.tv_cancelorder)
    TextView tv_cancelorder;
    @BindView(R.id.tv_page_title)
    TextView tv_page_title;
    @BindView(R.id.map_location)
    MapView map_location;
    @BindView(R.id.iv_head_img)
    CircleImageView iv_head_img;
    @BindView(R.id.ll_voice)
    LinearLayout ll_voice;
    @BindView(R.id.scroll_view)
    NestedScrollView scroll_view;
    @BindView(R.id.map_container)
    MapContainer map_container;

    private DataManager dataManager;

    private String order_sn;
    private LoginSucessBean userInfo;
    private SosDetailBean orderDetail;
    private String voicePath = "";

    private AMap aMap;
    private BitmapDescriptor mBitmapDescriptor;
    private ArrayList<String> imageList = new ArrayList<>();
    private String[] imageArray = new String[]{};

    private ImageAdapter imageAdapter;
    private int order_status;
    private int pay_status;
    private String from;

    private AnimationDrawable animationDrawable;

    private String[] maps={"com.autonavi.minimap","com.baidu.BaiduMap","com.tencent.map"};
    private String[] mapsName={"高德地图","百度地图","腾讯地图"};
    private List<String> appName;
    private OnOptionsSelectListener selectListener;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sos_detail);
        ButterKnife.bind(this);
        IMAudioManager.instance().init(this);
        Intent intent = getIntent();
        order_sn = intent.getStringExtra("id");
        order_status = intent.getIntExtra("order_status", -1);
        pay_status = intent.getIntExtra("pay_status", -1);
        from = intent.getStringExtra("from");
        userInfo = (LoginSucessBean) SaveBeanUtil.getBean(this, "vipInfo");
        animationDrawable = (AnimationDrawable) ll_voice.getBackground();
        initView();
        getSosDetail();
        initMap(savedInstanceState);


    }

    @Override
    protected void initView() {
        if ("send_list".equals(from)) {//从发单列表点进来的
            if (order_status == 0 && pay_status == 0) {//待接单
                tv_cancelorder.setText("撤单");
            } else if (order_status == 1 && pay_status == 1) {//服务中
                tv_cancelorder.setText("已完工");
            } else if (order_status == 2 && pay_status == 1) {//已完工
                tv_cancelorder.setText("再来一单");
            }
        } else {
            tv_confirm.setVisibility(View.VISIBLE);
            tv_confirm.setText("沟通");
            tv_confirm.setTextColor(getResources().getColor(R.color.black_color));
            iv_confirm2.setVisibility(View.VISIBLE);
            iv_confirm2.setImageResource(R.mipmap.zy_gt);
            tv_cancelorder.setVisibility(View.GONE);
        }

        map_container = (MapContainer) findViewById(R.id.map_container);
        map_container.setScrollView(scroll_view);

        tv_page_title.setText("SOS详情");
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        gridLayoutManager.setSmoothScrollbarEnabled(true);
        gridLayoutManager.setAutoMeasureEnabled(true);
        imageAdapter = new ImageAdapter(R.layout.item_image, imageList);
        rv_pic.setLayoutManager(gridLayoutManager);
        rv_pic.setHasFixedSize(true);

        rv_pic.setNestedScrollingEnabled(false);
        rv_pic.setAdapter(imageAdapter);

        imageAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                // 预览图片
                if (imageList.size()>0)
                {
                    List<LocalMedia> tempMediaList = new ArrayList<>();
                    for (String s : imageList) {
                        LocalMedia tempLocalMedia = new LocalMedia();
                        tempLocalMedia.setPath(s);
                        tempMediaList.add(tempLocalMedia);
                    }
                    PictureSelector.create(SosDetailActivity.this).themeStyle(R.style.picture_default_style).openExternalPreview(position, tempMediaList);
                }
            }
        });
    }


    private void initMap(Bundle savedInstanceState) {
        appName=new ArrayList<>();
        map_location.onCreate(savedInstanceState);// 此方法必须重写
        aMap = map_location.getMap();
        aMap.getUiSettings().setMyLocationButtonEnabled(false);//设置默认定位按钮是否显示，非必需设置。
//        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.getUiSettings().setAllGesturesEnabled(false);
        aMap.getUiSettings().setZoomGesturesEnabled(true);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(15));
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                appName.clear();
                for (int i = 0; i < maps.length; i++) {
                    if(CheckApplacationUtil.isAvailable(SosDetailActivity.this,maps[i]))
                        appName.add(mapsName[i]);
                }
                if(appName.size()>0){
                    PickerViewUtils.customOptionPickerView(appName, selectListener);
                }else{
                    DisplayUtil.diaplayLongToast(SosDetailActivity.this,"您未安装高德,百度,腾讯地图");
                }
            }
        });

    }


    private void initOptionsSelectListener(final SosDetailBean orderDetail) {
        selectListener = new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                String mapName = appName.get(options1);
                if ("高德地图".equals(mapName)) {
                    Intent intent = new Intent("android.intent.action.VIEW",
                            android.net.Uri.parse("androidamap://route?sourceApplication=baletu&dlon=" + orderDetail.getLongitude() + "&dlat=" + orderDetail.getLatitude() + "&dev=0&t=0"));
                    intent.setPackage("com.autonavi.minimap");
                    startActivity(intent);
                } else if ("百度地图".equals(mapName)) {

                    String bd_lat = "";
                    String bd_lon = "";
                    try {
                        bd_lat = GPSUtil.gcj02_To_Bd09(Double.parseDouble(orderDetail.getLatitude()),Double.parseDouble(orderDetail.getLongitude()))[0]+"";
                        bd_lon = GPSUtil.gcj02_To_Bd09(Double.parseDouble(orderDetail.getLatitude()),Double.parseDouble(orderDetail.getLongitude()))[1]+"";
                    } catch (Exception e) {
                        bd_lat = orderDetail.getLatitude();
                        bd_lon = orderDetail.getLongitude();
                    }

                    Intent intent = new Intent();
                    try {
                        intent.setData(Uri.parse("baidumap://map/direction?destination=latlng:"+bd_lat+","+bd_lon+"|name:"+orderDetail.getWeizhi()+"&mode=driving"));
//                        intent = Intent.getIntent("intent://map/direction?destination=latlng:" + orderDetail.getLongitude()+","+ orderDetail.getLatitude() +"|name:"+ orderDetail.getWeizhi() + "&mode=driving&src=baletu#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                        startActivity(intent);
                    } catch (Exception e) {

                    }

                } else if ("腾讯地图".equals(mapName)) {
                    Intent intent = null;
                    try {
                        intent = Intent.getIntent("qqmap://map/routeplan?to=" + orderDetail.getWeizhi() + "&tocoord="  + orderDetail.getLongitude()+","+ orderDetail.getLatitude() + "&referer=一键帮&type=drive");
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                    startActivity(intent);
                }
            }
        };
    }


    private void getSosDetail() {
        dataManager = new DataManager();
        Map<String, String> map = new HashMap<>();
        map.put("id", order_sn + "");
        ObserverOnNextListener<SosDetailBean> listener = new ObserverOnNextListener<SosDetailBean>() {
            @Override
            public void onNext(SosDetailBean orderDetailBean) {
                setData(orderDetailBean);
                initOptionsSelectListener(orderDetailBean);
            }
        };
        dataManager.sosDetail(new ProgressObserver<SosDetailBean>(listener, this), map);
    }


    private void setData(SosDetailBean orderDetail) {
        this.orderDetail = orderDetail;
        tv_orderdetail_id.setText(orderDetail.getId()+"");
//        tv_order_type.setText(orderDetail.getCat_type_name());
        tv_order_endtime.setText(orderDetail.getAddtime().toString()+"");
        GlideApp.with(this).load(HostUrl.HOSTPIC +orderDetail.getFace_img()).into(iv_head_img);
        tv_content.setText(orderDetail.getOrign_remark());
        tv_user_name.setText(orderDetail.getNickname());

        if (TextUtils.isEmpty(orderDetail.getVoice()))
        {
            ll_voice.setVisibility(View.GONE);
        }
        else
        {
            ll_voice.setVisibility(View.VISIBLE);
        }
        this.mBitmapDescriptor = BitmapDescriptorFactory.fromResource(R.mipmap.zy_dtdw);

        String latitude = orderDetail.getLatitude();
        String longitude = orderDetail.getLongitude();
        if (!TextUtils.isEmpty(latitude) && !TextUtils.isEmpty(longitude)) {
            LatLng latLng = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
            MarkerOptions markerOptions = (new MarkerOptions()).position(latLng).icon(this.mBitmapDescriptor);
            aMap.addMarker(markerOptions);
            CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng, 15, 0, 0));
            aMap.moveCamera(cameraUpdate);
        }


        if (!TextUtils.isEmpty(orderDetail.getPicture())) {
            imageArray = orderDetail.getPicture().split(",");
            if (imageArray != null && imageArray.length > 0) {
                imageList.clear();
                for (int i = 0; i < imageArray.length; i++) {
                    imageList.add(HostUrl.HOSTPIC + imageArray[i]);
                }
            }
            imageAdapter.notifyDataSetChanged();
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (animationDrawable!=null&&animationDrawable.isRunning())
            animationDrawable.stop();
    }

    @OnClick({R.id.iv_back, R.id.tv_confirm, R.id.iv_confirm2, R.id.tv_cancelorder, R.id.ll_voice,R.id.map_location})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.map_location:
                /*appName.clear();
                for (int i = 0; i < maps.length; i++) {
                    if(CheckApplacationUtil.isAvailable(OrderDetailActivity.this,maps[i]))
                        appName.add(mapsName[i]);
                }
                if(appName.size()>0){
                    PickerViewUtils.customOptionPickerView(appName, selectListener);
                }else{
                    DisplayUtil.diaplayLongToast(OrderDetailActivity.this,"您未安装高德,百度,腾讯地图");
                }*/
                break;
            case R.id.tv_confirm:
//                RongChatUtils.startPrivateChat(OrderDetailActivity.this, user_id, user_id, null);
                bindOrderToUser();

                break;
            case R.id.iv_confirm2:
                bindOrderToUser();

                break;
            case R.id.tv_cancelorder:// 撤单/已完工
                if (orderDetail==null) {
                    return;
                }
                if (order_status == 0 && pay_status == 0) {//待接单
//                    getreason();// 获取撤单原因并撤单
                } else if (order_status == 1 && pay_status == 1) {//服务中
                    orderConfirm();//完工
                } else if (order_status == 2 && pay_status == 1) {//已完工
                    finish();//再来一单
                }

                break;
            case R.id.ll_voice:
                if (animationDrawable!=null&&!animationDrawable.isRunning())
                    animationDrawable.start();
                IMAudioManager.instance().playSound(HostUrl.HOSTPIC + orderDetail.getVoice(), new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
//                        Toast.makeText(SosDetailActivity.this, "播放结束", Toast.LENGTH_SHORT).show();
                        if (animationDrawable!=null&&animationDrawable.isRunning())
                            animationDrawable.stop();
                        ll_voice.setBackground(getResources().getDrawable(R.drawable.voice_anim));
                    }
                });
               /* EaseChatRowVoicePlayer voicePlayer = EaseChatRowVoicePlayer.getInstance(SosDetailActivity.this);
                voicePlayer.play(HostUrl.HOSTPIC + orderDetail.getVoice(), new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        if (animationDrawable!=null&&animationDrawable.isRunning())
                            animationDrawable.stop();
                        // Stop the voice play animation.
                    }
                });*/
                break;
        }
    }

    //完成订单
    private void orderConfirm() {
        final String request_id = orderDetail.getUid()+"";
        if (request_id.equals("0"))
            return;
        DataManager dataManager = new DataManager();
        Map<String, String> map = new HashMap<>();
        map.put("order_id", orderDetail.getId() + "");
//        map.put("title", orderDetail.getCat_type_name());
        ObserverOnNextListener<Object> listener = new ObserverOnNextListener<Object>() {
            @Override
            public void onNext(Object Object) {

            }
        };
        dataManager.orderConfirm(new ProgressObserver<Object>(listener, this), map);
    }

    //获取撤单原因
    private void getreason() {
        DataManager dataManager = new DataManager();
        ObserverOnNextListener<List<ReasonBean>> listener = new ObserverOnNextListener<List<ReasonBean>>() {
            @Override
            public void onNext(List<ReasonBean> reasonBeanList) {
                String[] strArra = new String[reasonBeanList.size()];
                for (int i = 0; i < reasonBeanList.size(); i++) {
                    strArra[i] = reasonBeanList.get(i).getReason();
                }
                showPP(strArra);
            }
        };
        dataManager.getreason(new ProgressObserver<List<ReasonBean>>(listener, this));
    }

    /**
     * 弹出选择撤单原因
     * @param
     */
    private void showPP(String[] strArra) {

        DisplayUtil.diaplayDialog(this, "性别", strArra, null, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String reason = (String) v.getTag();
                cancelororder(reason);
            }
        });
    }


    /**
     *
     * @param reason 撤单原因
     */
    private void cancelororder(String reason) {
        final String request_id = orderDetail.getUid()+"";
        if (request_id.equals("0"))
            return;
        DataManager dataManager = new DataManager();
        Map<String, String> map = new HashMap<>();
        map.put("order_id", orderDetail.getId() + "");
        map.put("reason", reason);
        ObserverOnNextListener<Object> listener = new ObserverOnNextListener<Object>() {
            @Override
            public void onNext(Object Object) {
                ToastUtils.show(getApplication(),"撤单成功!");
                finish();
            }
        };
        dataManager.cancelororder(new ProgressObserver<Object>(listener, this), map);
    }


    private void bindOrderToUser() {
        if (orderDetail==null)
            return;
        final String request_id = orderDetail.getUid()+"";
        if (request_id.equals("0"))
            return;
        DataManager dataManager = new DataManager();
        Map<String, String> map = new HashMap<>();
        map.put("order_id", orderDetail.getId() + "");
        map.put("chatuid", request_id + "");
        map.put("order_sn", order_sn);
        map.put("request_uid", request_id + "");
        map.put("response_uid", userInfo.getUid() + "");
        map.put("origin", "sos");
        ObserverOnNextListener<Object> listener = new ObserverOnNextListener<Object>() {
            @Override
            public void onNext(Object Object) {
                Map<String, String> map = new HashMap<>();
                map.put("order_sn", order_sn);
                RongChatUtils.startPrivateChat(SosDetailActivity.this,
                        request_id + "", request_id + "", map);
            }
        };
        dataManager.bindOrderToUser(new ProgressObserver<Object>(listener, this), map);
    }
}
